<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <a-card :bordered="false">
      <h3 style="margin-bottom: 20px;">JNBY-天目里车位摇号</h3>
      <a-form-model ref="rulesForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 3 }, sm: { span: 3 } }" :wrapperCol="{ lg: { span: 21 }, sm: { span: 21 } }">
        <a-form-model-item style="margin-bottom: 0;" label="年份" class="hidden-title">
          <a-row :gutter="10">
            <a-col :xxl="10" :xl="10" :lg="10" :sm="24">
              <a-row>
                <a-col :xxl="12" :xl="12" :lg="12" :sm="12">
                  <a-form-model-item prop="year">
                    <a-date-picker
                      mode="year"
                      :disabled="oneWheelRewardFlag"
                      style="width:80%;"
                      placeholder="请选择年份"
                      format='YYYY'
                      v-model="form.year"
                      :open='yearShowOne'
                      @change="handChange"
                      @openChange="openChangeOne"
                      @panelChange="panelChangeOne"/>
                      年
                  </a-form-model-item>
                </a-col>
                <a-col :xxl="12" :xl="12" :lg="12" :sm="12">
                  <a-form-model-item prop="period">
                    第
                    <a-select :disabled="oneWheelRewardFlag" @change="validate" v-model="form.period" style="width:60%;" placeholder="请选择" show-search :filter-option="filterOption" >
                      <a-select-option v-for="period in periods" :value="period" :key="period">{{ period }}</a-select-option>
                    </a-select>
                    期
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col :xxl="14" :xl="14" :lg="14" :sm="24">
              <a-form-model-item label="生效时间" :labelCol="{ span: 4 }" class="show-title" prop="time">
                <a-range-picker
                  :disabled="oneWheelRewardFlag"
                  style="width:75%;"
                  show-time
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  v-model="form.time"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item label="总车位数" prop="totalNumber">
          <a-input-number :disabled="oneWheelRewardFlag" v-model.trim="form.totalNumber" :min="0" style="width: 300px;margin-right: 10px;"  />
        </a-form-model-item>
        <a-form-model-item label="一轮车位数" prop="oneWheelNumber">
          <a-input-number :disabled="oneWheelRewardFlag" v-model.trim="form.oneWheelNumber" :min="0" :max="Number(form.totalNumber)" style="width: 300px;margin-right: 10px;"  /> <a-button @click="handleSubmit(1)" :disabled="oneWheelRewardFlag" type="primary">一轮抽奖</a-button>
        </a-form-model-item>
        <a-form-model-item label="二轮车位数" required>
          <a-input-number disabled v-model.trim="twoWheelNumber" :min="0" style="width: 300px;margin-right: 10px;"  /> <a-button @click="handleSubmit(2)" :disabled="twoWheelRewardFlag || !oneWheelRewardFlag" type="primary">二轮抽奖</a-button>
        </a-form-model-item>
      </a-form-model>
      <a-row :gutter="20">
        <a-col :xxl="12" :xl="12" :lg="12" :sm="24">
          <div style="display: flex;align-items: center;">
            <a-tabs default-active-key="1" style="flex: 1;">
              <a-tab-pane key="1" tab="一轮参与名单">
              </a-tab-pane>
            </a-tabs>
            <a-upload
              accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              name="file"
              :showUploadList="false"
              :multiple="false"
              :data="uploadData"
              :action="uploadUrl"
              @change="handleOneWheelRewardChange"
            >
              <a-button type="primary" shape="round" style="margin-left: 15px;">导入名单</a-button>
            </a-upload>
          </div>
          <a-table style="margin-top: 10px;" :pagination="oneWheelRewardPagination" bordered :columns="memberColumns" :data-source="oneWheelReward"
          :rowKey="(record, index) => index" size="middle" @change="oneWheelRewardPageChange">
          </a-table>
        </a-col>
        <a-col :xxl="12" :xl="12" :lg="12" :sm="24">
          <div style="display: flex;align-items: center;">
            <a-tabs default-active-key="1" style="flex: 1;">
              <a-tab-pane key="1" tab="二轮参与名单">
              </a-tab-pane>
            </a-tabs>
            <a-upload
              accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              name="file"
              :showUploadList="false"
              :multiple="false"
              :data="uploadData"
              :action="uploadUrl"
              @change="handleTwoWheelRewardChange"
            >
              <a-button type="primary" shape="round" style="margin-left: 15px;">导入名单</a-button>
            </a-upload>
          </div>
          <a-table style="margin-top: 10px;" :pagination="twoWheelRewardPagination" bordered :columns="memberColumns" :data-source="twoWheelReward"
          :rowKey="(record, index) => index" size="middle" @change="twoWheelRewardPageChange">
          </a-table>
        </a-col>
      </a-row>
      <div style="display: flex;align-items: center;">
        <a-tabs default-active-key="1" style="flex: 1;">
          <a-tab-pane key="1" tab="中奖名单">
          </a-tab-pane>
        </a-tabs>
        <a-button type="primary" style="margin-left: 15px;" shape="round" @click="handleExportReward">导出</a-button>
        <a-button style="margin-left: 15px;background: #ebd28d;border: none;color: #fff;" shape="round" @click="handleSendMessage">推送钉钉消息</a-button>
      </div>
      <a-table style="margin-top: 10px;" :pagination="winnerPagination" bordered :columns="columns" :data-source="winners"
      :rowKey="(record, index) => index" size="middle" @change="winnerPageChange">
      </a-table>
    </a-card>
  </a-spin>
</template>
<script>
import { spaceImport, oneWheelReward, twoWheelReward, exportReward, message } from '@/api/parkingPlace/index'

import moment from 'moment'
const memberColumns = [
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'userName'
    },
    {
      title: '工号',
      align: 'center',
      dataIndex: 'linkId'
    },
    {
      title: '部门',
      align: 'center',
      dataIndex: 'department'
    }
  ]
  const columns = [
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'userName'
    },
    {
      title: '工号',
      align: 'center',
      dataIndex: 'linkId'
    },
    {
      title: '部门',
      align: 'center',
      dataIndex: 'department'
    },
    {
      title: '轮数',
      align: 'center',
      dataIndex: 'roundsNumber'
    }
  ]
  const ruleInteger = [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const reg = /^[0-9]*[1-9][0-9]*$/
        if (!value) {
          callback()
        } else {
          if (reg.test(value)) {
            callback()
          } else {
            return callback(new Error('请输入正确的格式'))
          }
        }
      },
      trigger: 'blur'
    }
  ]
  const periods = []
  for(let i = 1; i < 11; i++) {
    periods.push(i)
  }
  const pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: total => `共有 ${total} 条数据`
  }
export default {
  components: {
  },
  data() {
    return {
      periods,
      columns,
      yearShowOne: false,
      oneWheelRewardPagination: pagination,
      twoWheelRewardPagination: pagination,
      winnerPagination: pagination,
      memberColumns,
      oneWheelReward: [],
      oneWheelRewardFlag: false,
      twoWheelReward: [],
      twoWheelRewardFlag: false,
      winners: [],
      uploadData: {},
      uploadUrl: spaceImport,
      spinning: false,
      form: {
        year: null,
        time: [],
        totalNumber: ''
      },
      rules: {
        time: [{ required: true, message: '请选择', trigger: 'change' }],
        year: [{ required: true, message: '请选择', trigger: 'change' }],
        period: [{ required: true, message: '请选择', trigger: 'change' }],
        oneWheelNumber: ruleInteger,
        totalNumber: ruleInteger
      }
    }
  },
  watch: {
  },
  activated() {
  },
  created() {
  },
  computed: {
    twoWheelNumber() {
      return this.form.totalNumber - this.form.oneWheelNumber || 0
    }
  },
  mounted() {},
  methods: {
    // 年份选择器
    handChange() {
      this.form.year = null
    },

    // 年份选择器
    openChangeOne(status) {
      this.yearShowOne = status
    },

    // 得到年份选择器的值
    panelChangeOne(value) {
      this.form.year = moment(value).format('YYYY')
      this.yearShowOne = false;
      this.$refs.rulesForm.validate()
    },

    // 导出中奖记录
    handleExportReward() {
      if (!this.winners.length) {
        this.$message.error('名单为空！')
        return
      }
      window.location.href = exportReward + `?rewardCode=${this.winners[0].rewardCode}`
    },

    // 推送钉钉消息
    handleSendMessage() {
      // if (!this.winners.length) {
      //   this.$message.error('名单为空！')
      //   return
      // }
      const data = {
        rewardCode: this.winners.length ? this.winners[0].rewardCode : null
      }
      this.spinning = true
      message(data).then(res => {
        if (res.code === 200) {
          this.spinning = false
          this.$message.success('消息推送成功！')
        } else {
          this.spinning = false
          this.$message.error(res.msg || res.message)
        }
      }).catch(err => {
        this.spinning = false
      })
    },
    

    // 导入名单
    handleOneWheelRewardChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        const {msg, message, code, data} = info.file.response
        if (code == 200 ) {
          this.oneWheelReward = data
          this.oneWheelRewardPagination.current = 1
        } else {
          this.$message.error(msg || message)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
    },

    handleTwoWheelRewardChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        const {msg, message, code, data} = info.file.response
        if (code == 200 ) {
          this.twoWheelReward = data
          this.twoWheelRewardPagination.current = 1
        } else {
          this.$message.error(msg || message)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
    },


    // 分页change
    oneWheelRewardPageChange(pagination) {
      const pager = { ...this.oneWheelRewardPagination }
      pager.current = pagination.current
      this.oneWheelRewardPagination = pager
    },

    // 分页change
    twoWheelRewardPageChange(pagination) {
      const pager = { ...this.twoWheelRewardPagination }
      pager.current = pagination.current
      this.twoWheelRewardPagination = pager
    },

    // 分页change
    winnerPageChange(pagination) {
      const pager = { ...this.winnerPagination }
      pager.current = pagination.current
      this.winnerPagination = pager
    },
    
    // 抽签
    handleSubmit(type) {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          const { time, oneWheelNumber } = this.form
          // type 1 一轮， 2 二轮
          if ((type == 1 && !this.oneWheelReward.length) || (type == 2 && !this.twoWheelReward.length)) {
            this.$message.error('请导入名单！')
            return
          }
          if ((type == 1 && !oneWheelNumber) || (type == 2 && !this.twoWheelNumber)) {
            this.$message.error('车位数为0不可以抽签哦！')
            return
          }
          const data = {
            ...this.form,
            oneWheelNumber: type == 1 ? oneWheelNumber : null,
            twoWheelNumber: type == 2 ? this.twoWheelNumber : null,
            startTime: time[0],
            endTime: time[1],
            oneUserCode: type == 1 ? this.oneWheelReward[0].userCode : null,
            twoUserCode: type == 2 ? this.twoWheelReward[0].userCode : null,
            rewardCode: type == 2 && this.winners.length ? this.winners[0].rewardCode : null
          }
          const reward = type == 1 ? oneWheelReward : twoWheelReward
          this.spinning = true
          this.winners = []
          reward(data).then(res => {
            if (res.code === 200) {
              this.spinning = false
              this.winners = res.data
              this.winnerPagination.current = 1
              type == 1 ? this.oneWheelRewardFlag = true : this.twoWheelRewardFlag = true
            } else {
              this.spinning = false
              this.$message.error(res.msg || res.message)
            }
          }).catch(err => {
            this.spinning = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    //返回
    handleBack() {
      this.$router.go(-1)
    },

    validate() {
      this.$refs.rulesForm.validate()
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  }
}
</script>
<style lang="less" scoped>
.hidden-title /deep/ .ant-form-item-label label {
    visibility: hidden;
}
.show-title /deep/ .ant-form-item-label label {
    visibility: visible;
}
</style>
